package com.carb.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carb.constant.MessageConstant;
import com.carb.context.UserContext;
import com.carb.dto.BusinessAddDTO;
import com.carb.dto.BusinessPageQueryDTO;
import com.carb.dto.ItemStockUpdateDTO;
import com.carb.entity.*;
import com.carb.enums.*;
import com.carb.exception.AccountNotFoundException;
import com.carb.exception.BusinessErrorException;
import com.carb.exception.EntityNotFoundException;
import com.carb.mapper.*;
import com.carb.query.PageQueryUtils;
import com.carb.result.PageResult;
import com.carb.service.IBusinessService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carb.service.IItemService;
import com.carb.vo.BusinessVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务管理 服务实现类
 * </p>
 *
 * @author XuChaoyang
 * @since 2025-01-18
 */
@Service
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements IBusinessService {

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private EmployeeMapper employeeMapper;

    @Resource
    private MemberMapper memberMapper;

    @Resource
    private CarMapper carMapper;

    @Resource
    private ProjectItemMapper projectItemMapper;

    @Resource
    private IItemService itemService;

    @Resource
    private FeedbackMapper feedbackMapper;

    /**
     * 新增业务
     * @param businessAddDTO 新增业务数据模型
     */
    @Override
    @Transactional
    public void addBusiness(BusinessAddDTO businessAddDTO) {
        // 1、对象属性拷贝
        Business business = new Business();
        BeanUtils.copyProperties(businessAddDTO, business);

        // 2、检查服务项目是否存在，是否禁用
        Project project = projectMapper.selectOne(Wrappers.lambdaQuery(Project.class)
                .eq(Project::getId, businessAddDTO.getProjectId())
                .eq(Project::getDeleted, CommonDeleted.NOT_DELETED));
        checkProjectAndMemberStatus(businessAddDTO, project);

        // 3、填充付款方式、业务状态（待接单）、应付金额
        BusinessPayMethod payMethod = businessAddDTO.getPayMethod();
        business.setPayMethod(payMethod);
        business.setStatus(BusinessStatus.UNACCEPTED);
        // 3.1、应付金额 (单位为分)
        MemberLevel level = memberMapper.selectById(businessAddDTO.getMemberId()).getLevel();
        double discountRate = switch (level) {
            case ORDINARY -> 1.0;    // 普通不打折
            case SILVER   -> 0.95;   // 银卡9.5折
            case GOLD     -> 0.85;   // 金卡8.5折
            case SUPREME  -> 0.7;    // 至尊7折
        };
        business.setPayableAmount((int) (project.getPrice() * discountRate));

        // 4、新增业务
        this.save(business);

        // 5、扣减会员余额
        if (payMethod == BusinessPayMethod.BALANCE) {
            deductMemberBalance(business);
        }

        // 6、扣减该业务对应的服务项目所使用的物品库存数量
        // 6.1、根据服务项目id查询服务项目物品关联信息
        List<ProjectItem> projectItemList = projectItemMapper.selectList(Wrappers.lambdaQuery(ProjectItem.class)
                .eq(ProjectItem::getProjectId, business.getProjectId()));
        // 6.2、构造物品库存更新DTO列表
        List<ItemStockUpdateDTO> itemStockUpdateDTOList = projectItemList.stream()
                .map(projectItem -> new ItemStockUpdateDTO()
                        .setId(projectItem.getItemId())
                        .setQuantity(projectItem.getQuantity())
                        .setNote(MessageConstant.ITEM_STOCK_OUT_BUSINESS_PAY))
                .toList();
        // 6.3、扣减库存数量，物品出库
        itemService.reduceItemStock(itemStockUpdateDTOList);

        // 7、新增初始评价（评分0、禁止评价）
        feedbackMapper.insert(new Feedback()
                .setBusinessId(business.getId())
                .setRating(0)
                .setContent(MessageConstant.FORBID_FEEDBACK)
                .setStatus(FeedbackStatus.FORBID_FEEDBACK));
    }

    /**
     * 业务分页查询
     * @param businessPageQueryDTO 查询条件
     * @return 业务分页结果
     */
    @Override
    public PageResult<BusinessVO> pageQuery(BusinessPageQueryDTO businessPageQueryDTO) {
        // 1、获取查询属性
        // 1.1、分页属性
        Long pageNum = PageQueryUtils.checkPageNum(businessPageQueryDTO.getPageNum());
        Long pageSize = PageQueryUtils.checkPageSize(businessPageQueryDTO.getPageSize());
        String orderBy = businessPageQueryDTO.getOrderBy();
        Boolean isAsc = businessPageQueryDTO.getIsAsc();
        // 1.2、查询属性
        String projectName = businessPageQueryDTO.getProjectName();
        Long projectTypeId = businessPageQueryDTO.getProjectTypeId();
        String employeeName = businessPageQueryDTO.getEmployeeName();
        String memberName = businessPageQueryDTO.getMemberName();
        String plateNumber = businessPageQueryDTO.getPlateNumber();
        BusinessPayMethod payMethod = businessPageQueryDTO.getPayMethod();
        BusinessStatus businessStatus = businessPageQueryDTO.getBusinessStatus();
        LocalDateTime startTime = businessPageQueryDTO.getStartTime();
        LocalDateTime endTime = businessPageQueryDTO.getEndTime();

        // 2、构造条件
        // 2.1、分页条件
        Page<Business> page = Page.of(pageNum, pageSize);
        // 2.2、排序条件
        PageQueryUtils.applySorting(page, orderBy, isAsc);
        // 2.3、空结果
        PageResult<BusinessVO> emptyPageResult = new PageResult<>(page.getTotal(), page.getPages(), Collections.emptyList());

        // 3、根据服务项目名称+服务项目类型id（不同时为空），得到服务项目id集合
        List<Long> projectIdList = new ArrayList<>();
        if (projectName != null || projectTypeId != null) {
            projectIdList = projectMapper.getProjectIdsByProjectNameOrType(projectName, projectTypeId);
            if (projectIdList.isEmpty()) return emptyPageResult;
        }

        // 4、根据员工姓名（不为空），得到员工id集合
        List<Long> employeeIdList = new ArrayList<>();
        if (employeeName != null) {
            // 4.1、根据员工姓名查询员工的用户id
            List<Long> employeeUserIdList = userMapper.getUserIdsByName(employeeName, UserRole.EMPLOYEE);
            if (employeeUserIdList.isEmpty()) return emptyPageResult;
            // 4.2、根据员工的用户id查询员工id
            employeeIdList = employeeMapper.getEmployeeIdsByUserIds(employeeUserIdList);
            if (employeeIdList.isEmpty()) return emptyPageResult;
        }

        // 5、根据会员姓名（不为空），得到会员id集合
        List<Long> memberIdList = new ArrayList<>();
        if (memberName != null) {
            // 5.1、根据会员姓名查询会员的用户id
            List<Long> memberUserIdList = userMapper.getUserIdsByName(memberName, UserRole.MEMBER);
            if (memberUserIdList.isEmpty()) return emptyPageResult;
            // 5.2、根据会员的用户id查询会员id
            memberIdList = memberMapper.getMemberIdsByUserIds(memberUserIdList);
            if (memberIdList.isEmpty()) return emptyPageResult;
        }

        // 6、根据车牌号（不为空），得到车辆id集合
        List<Long> carIdList = new ArrayList<>();
        if (plateNumber != null) {
            carIdList = carMapper.getCarIdsByPlateNumber(plateNumber);
            if (carIdList.isEmpty()) return emptyPageResult;
        }

        // 7、业务表查询（服务项目id、员工id、会员id、车辆id、付款方式、付款状态、业务状态、开始时间≤创建时间≤结束时间）
        Page<Business> businessPage = this.page(page, Wrappers.lambdaQuery(Business.class)
                .in(projectName != null || projectTypeId != null, Business::getProjectId, projectIdList)
                .in(employeeName != null, Business::getEmployeeId, employeeIdList)
                .in(memberName != null, Business::getMemberId, memberIdList)
                .in(plateNumber != null, Business::getCarId, carIdList)
                .eq(payMethod != null, Business::getPayMethod, payMethod)
                .eq(businessStatus != null, Business::getStatus, businessStatus)
                .ge(startTime != null, Business::getCreateTime, startTime)
                .le(endTime != null, Business::getCreateTime, endTime));
        if (businessPage.getTotal() == 0) return emptyPageResult;

        // 8、使用in查询一次性获取所有关联数据
        // 8.1、获取所有关联数据的id集合
        List<Long> projectIds = new ArrayList<>();
        List<Long> employeeIds = new ArrayList<>();
        List<Long> memberIds = new ArrayList<>();
        List<Long> carIds = new ArrayList<>();
        for (Business business : businessPage.getRecords()) {
            projectIds.add(business.getProjectId());
            employeeIds.add(business.getEmployeeId());
            memberIds.add(business.getMemberId());
            carIds.add(business.getCarId());
        }
        // 8.2、获取所有关联数据的id-name集合
        Map<Long, String> projectNameMap = projectMapper.getProjectNamesByIds(projectIds).stream()
                .collect(Collectors.toMap(map -> Long.valueOf(map.get("projectId").toString()), map -> map.get("projectName").toString()));
        Map<Long, String> employeeNameMap = employeeMapper.getEmployeeNamesByIds(employeeIds).stream()
                .collect(Collectors.toMap(map -> Long.valueOf(map.get("employeeId").toString()), map -> map.get("employeeName").toString()));
        Map<Long, String> memberNameMap = memberMapper.getMemberNamesByIds(memberIds).stream()
                .collect(Collectors.toMap(map -> Long.valueOf(map.get("memberId").toString()), map -> map.get("memberName").toString()));
        Map<Long, String> carPlateNumberMap = carMapper.getCarPlateNumbersByIds(carIds).stream()
                .collect(Collectors.toMap(map -> Long.valueOf(map.get("carId").toString()), map -> map.get("plateNumber").toString()));

        // 9、封装VO数据列表
        List<BusinessVO> businessVOList = new ArrayList<>();
        for (Business business : businessPage.getRecords()) {
            BusinessVO businessVO = new BusinessVO();
            BeanUtils.copyProperties(business, businessVO);
            businessVO.setProjectName(projectNameMap.get(business.getProjectId()));
            businessVO.setEmployeeName(employeeNameMap.get(business.getEmployeeId()));
            businessVO.setMemberName(memberNameMap.get(business.getMemberId()));
            businessVO.setCarPlateNumber(carPlateNumberMap.get(business.getCarId()));
            businessVOList.add(businessVO);
        }

        // 10、将实体分页对象转换为VO分页对象
        Page<BusinessVO> businessVOPage = PageQueryUtils.convertToVOPage(businessPage, businessVOList);

        // 11、返回封装结果
        return new PageResult<>(businessVOPage.getTotal(), businessVOPage.getPages(), businessVOPage.getRecords());
    }

    /**
     * 根据业务id查询业务信息
     * @param id 业务id
     * @return 查询结果
     */
    @Override
    public BusinessVO getBusinessById(Long id) {
        // 1、获取业务信息
        Business business = this.getById(id);
        if (business == null) {
            // 业务不存在
            throw new EntityNotFoundException(MessageConstant.BUSINESS_NOT_FOUND);
        }

        // 2、封装VO
        BusinessVO businessVO = new BusinessVO();
        BeanUtils.copyProperties(business, businessVO);
        businessVO.setProjectName(projectMapper.selectById(business.getProjectId()).getName())
                .setEmployeeName(employeeMapper.getNameByEmployeeId(business.getEmployeeId()))
                .setMemberName(memberMapper.getNameByMemberId(business.getMemberId()))
                .setCarPlateNumber(carMapper.selectById(business.getCarId()).getPlateNumber());

        // 3、返回VO
        return businessVO;
    }

    /**
     * 业务接单
     * @param id 业务id
     */
    @Override
    @Transactional
    public void acceptBusiness(Long id) {
        // 1、检查业务是否存在
        Business business = this.getById(id);
        if (business == null) {
            // 业务不存在
            throw new EntityNotFoundException(MessageConstant.BUSINESS_NOT_FOUND);
        }

        // 2、检查业务状态是否为待接单
        if (business.getStatus() != BusinessStatus.UNACCEPTED) {
            // 业务已接单或已结束，接单失败
            throw new BusinessErrorException(MessageConstant.BUSINESS_ACCEPT_ERROR);
        }

        // 3、获取当前登录员工id
        Long employeeId = employeeMapper.selectOne(Wrappers.lambdaQuery(Employee.class)
                .eq(Employee::getUserId, UserContext.getUserId()))
                .getId();

        // 4、更新员工id、业务状态为进行中
        this.update(new Business(), Wrappers.lambdaUpdate(Business.class)
                .eq(Business::getId, id)
                .set(Business::getEmployeeId, employeeId)
                .set(Business::getStatus, BusinessStatus.IN_PROGRESS));
    }

    /**
     * 完成业务
     * @param id 业务id
     */
    @Override
    @Transactional
    public void completeBusiness(Long id) {
        // 1、根据业务id查询业务信息
        Business business = this.getById(id);
        if (business == null) {
            // 业务不存在
            throw new EntityNotFoundException(MessageConstant.BUSINESS_NOT_FOUND);
        }

        // 2、校验业务状态（进行中）才能正常完成业务
        checkCompleteOrRefundBusiness(business, false);

        // 3、更新会员上次服务时间、积分、服务总次数
        // 3.1、会员信息
        Long memberId = business.getMemberId();
        Member member = memberMapper.selectById(memberId);
        Integer memberPoints = member.getPoints();
        Integer memberTotalServicesCount = member.getTotalServicesCount();
        // 3.2、实付金额 (单位为分)
        Integer payableAmount = business.getPayableAmount();
        // 3.3、更新会员信息（更新上次服务时间、积分:实付=1:1取整、服务总次数+1）
        memberMapper.update(new Member(), Wrappers.lambdaUpdate(Member.class)
                .eq(Member::getId, memberId)
                .set(Member::getLastServiceTime, LocalDateTime.now())
                .set(Member::getPoints, memberPoints + payableAmount / 100)
                .set(Member::getTotalServicesCount, memberTotalServicesCount + 1));

        // 4、更新车辆上次服务时间
        carMapper.update(new Car(), Wrappers.lambdaUpdate(Car.class)
                .eq(Car::getId, business.getCarId())
                .set(Car::getLastServiceTime, LocalDateTime.now()));

        // 5、计算实际服务时长（单位为分钟），当前时间减去创建时间
        long minutes = Duration.between(business.getCreateTime(), LocalDateTime.now()).toMinutes();

        // 6、更新业务信息（已完成、实际服务时长）
        this.update(new Business(), Wrappers.lambdaUpdate(Business.class)
                .eq(Business::getId, id)
                .set(Business::getStatus, BusinessStatus.COMPLETED)
                .set(Business::getActualDuration, minutes));

        // 7、更新评价状态为待评价
        feedbackMapper.update(new Feedback(), Wrappers.lambdaUpdate(Feedback.class)
                .eq(Feedback::getBusinessId, id)
                .set(Feedback::getContent, null)
                .set(Feedback::getStatus, FeedbackStatus.WAIT_FEEDBACK));
    }

    /**
     * 业务退款
     * @param id 业务id
     */
    @Override
    @Transactional
    public void refundBusiness(Long id) {
        // 1、根据业务id查询业务信息
        Business business = this.getById(id);
        if (business == null) {
            // 业务不存在
            throw new EntityNotFoundException(MessageConstant.BUSINESS_NOT_FOUND);
        }

        // 2、校验业务状态（未接单）才能正常退款
        checkCompleteOrRefundBusiness(business, true);

        // 3、退还会员余额
        if (business.getPayMethod() == BusinessPayMethod.BALANCE) {
            // 3.1、会员信息
            Long memberId = business.getMemberId();
            Member member = memberMapper.selectById(memberId);
            Integer balance = member.getBalance();
            // 3.2、退还会员余额
            memberMapper.update(new Member(), Wrappers.lambdaUpdate(Member.class)
                    .eq(Member::getId, memberId)
                    .set(Member::getBalance, balance + business.getPayableAmount()));
        }

        // 4、退还该业务对象的服务项目所使用的物品库存数量
        // 4.1、根据服务项目id查询服务项目物品关联信息
        List<ProjectItem> projectItemList = projectItemMapper.selectList(Wrappers.lambdaQuery(ProjectItem.class)
                .eq(ProjectItem::getProjectId, business.getProjectId()));
        // 4.2、构造物品库存更新DTO列表
        List<ItemStockUpdateDTO> itemStockUpdateDTOList = projectItemList.stream()
                .map(projectItem -> new ItemStockUpdateDTO()
                        .setId(projectItem.getItemId())
                        .setQuantity(projectItem.getQuantity())
                        .setNote(MessageConstant.ITEM_STOCK_OUT_BUSINESS_REFUND))
                .toList();
        // 4.3、退还库存数量，物品入库
        itemService.addItemStock(itemStockUpdateDTOList);

        // 5、更新业务信息（已退款）
        this.update(new Business(), Wrappers.lambdaUpdate(Business.class)
                .eq(Business::getId, id)
                .set(Business::getStatus, BusinessStatus.REFUNDED));
    }

    /**
     * 会员自身业务数量查询
     * @param businessStatus 业务状态
     * @return 业务数量
     */
    @Override
    public Long countBusinessForMember(BusinessStatus businessStatus) {
        // 1、获取当前登录会员id
        Long userId = UserContext.getUserId();
        Long memberId = memberMapper.getMemberIdsByUserIds(List.of(userId)).getFirst();

        // 2、查询并返回业务数量
        return this.count(Wrappers.lambdaQuery(Business.class)
                .eq(Business::getMemberId, memberId)
                .eq(Business::getStatus, businessStatus));
    }

    /**
     * 会员自身业务查询
     * @param businessStatus 业务状态
     * @return 业务列表
     */
    @Override
    public List<BusinessVO> listBusinessForMember(BusinessStatus businessStatus) {
        // 1、获取当前登录会员id
        Long userId = UserContext.getUserId();
        Long memberId = memberMapper.getMemberIdsByUserIds(List.of(userId)).getFirst();

        // 2、查询业务
        List<Business> businessList = this.list(Wrappers.lambdaQuery(Business.class)
                .eq(Business::getMemberId, memberId)
                .eq(Business::getStatus, businessStatus)
                .orderByDesc(Business::getCreateTime));
        if (businessList.isEmpty()) return Collections.emptyList();

        // 3、使用in查询一次性获取所有关联数据
        // 3.1、获取所有关联数据的id集合
        List<Long> projectIds = new ArrayList<>();
        List<Long> employeeIds = new ArrayList<>();
        List<Long> memberIds = new ArrayList<>();
        List<Long> carIds = new ArrayList<>();
        for (Business business : businessList) {
            projectIds.add(business.getProjectId());
            employeeIds.add(business.getEmployeeId());
            memberIds.add(business.getMemberId());
            carIds.add(business.getCarId());
        }
        // 3.2、获取所有关联数据的id-name集合
        Map<Long, String> projectNameMap = projectMapper.getProjectNamesByIds(projectIds).stream()
                .collect(Collectors.toMap(map -> Long.valueOf(map.get("projectId").toString()), map -> map.get("projectName").toString()));
        Map<Long, String> employeeNameMap = employeeMapper.getEmployeeNamesByIds(employeeIds).stream()
                .collect(Collectors.toMap(map -> Long.valueOf(map.get("employeeId").toString()), map -> map.get("employeeName").toString()));
        Map<Long, String> memberNameMap = memberMapper.getMemberNamesByIds(memberIds).stream()
                .collect(Collectors.toMap(map -> Long.valueOf(map.get("memberId").toString()), map -> map.get("memberName").toString()));
        Map<Long, String> carPlateNumberMap = carMapper.getCarPlateNumbersByIds(carIds).stream()
                .collect(Collectors.toMap(map -> Long.valueOf(map.get("carId").toString()), map -> map.get("plateNumber").toString()));

        // 4、封装VO数据列表
        List<BusinessVO> businessVOList = new ArrayList<>();
        for (Business business : businessList) {
            BusinessVO businessVO = new BusinessVO();
            BeanUtils.copyProperties(business, businessVO);
            businessVO.setProjectName(projectNameMap.get(business.getProjectId()));
            businessVO.setEmployeeName(employeeNameMap.get(business.getEmployeeId()));
            businessVO.setMemberName(memberNameMap.get(business.getMemberId()));
            businessVO.setCarPlateNumber(carPlateNumberMap.get(business.getCarId()));
            businessVOList.add(businessVO);
        }

        // 5、返回封装结果
        return businessVOList;
    }

    /**
     * 会员新增业务
     * @param businessAddDTO 新增业务数据模型
     */
    @Override
    @Transactional
    public void addBusinessForMember(BusinessAddDTO businessAddDTO) {
        // 1、获取当前登录会员id
        Long userId = UserContext.getUserId();
        Long memberId = memberMapper.getMemberIdsByUserIds(List.of(userId)).getFirst();
        businessAddDTO.setMemberId(memberId);

        // 2、新增业务
        this.addBusiness(businessAddDTO);
    }

    /**
     * 扣除会员余额
     * @param business 业务信息
     */
    private void deductMemberBalance(Business business) {
        // 1、应付金额 (单位为分)
        Integer payableAmount = business.getPayableAmount();

        // 2、会员信息
        Long memberId = business.getMemberId();
        Member member = memberMapper.selectById(memberId);
        Integer memberBalance = member.getBalance();

        // 3、判断会员余额是否充足
        if (memberBalance < payableAmount) {
            // 会员余额不足
            throw new BusinessErrorException(MessageConstant.MEMBER_BALANCE_NOT_ENOUGH);
        }

        // 4、扣除会员余额
        memberMapper.update(new Member(), Wrappers.lambdaUpdate(Member.class)
                .eq(Member::getId, memberId)
                .set(Member::getBalance, memberBalance - payableAmount));
    }

    /**
     * 检查项目状态和会员状态
     * @param businessAddDTO 新增业务数据模型
     * @param project 服务项目实体
     */
    private void checkProjectAndMemberStatus(BusinessAddDTO businessAddDTO, Project project) {
        // 1、检查服务项目是否存在
        if (project == null) {
            // 服务项目不存在
            throw new EntityNotFoundException(MessageConstant.PROJECT_NOT_FOUND);
        }
        if (project.getStatus() == CommonStatus.DISABLED) {
            // 服务项目已禁用
            throw new BusinessErrorException(MessageConstant.PROJECT_DISABLED);
        }

        // 2、检查会员是否存在
        Member member = memberMapper.selectOne(Wrappers.lambdaQuery(Member.class)
                .eq(Member::getId, businessAddDTO.getMemberId())
                .eq(Member::getDeleted, CommonDeleted.NOT_DELETED));
        if (member == null) {
            // 会员账号不存在
            throw new AccountNotFoundException(MessageConstant.MEMBER_ACCOUNT_NOT_FOUND);
        }

        // 3、检查会员对应的用户是否存在，是否禁用
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getId, member.getUserId())
                .eq(User::getDeleted, CommonDeleted.NOT_DELETED));
        if (user == null) {
            // 用户不存在
            throw new AccountNotFoundException(MessageConstant.USER_ACCOUNT_NOT_FOUND);
        }
        if (user.getStatus() == CommonStatus.DISABLED) {
            // 用户已禁用
            throw new BusinessErrorException(MessageConstant.MEMBER_DISABLED);
        }

        // 4、检查车辆是否存在
        Car car = carMapper.selectOne(Wrappers.lambdaQuery(Car.class)
                .eq(Car::getId, businessAddDTO.getCarId())
                .eq(Car::getDeleted, CommonDeleted.NOT_DELETED));
        if (car == null) {
            // 车辆不存在
            throw new EntityNotFoundException(MessageConstant.CAR_NOT_FOUND);
        }
    }

    /**
     * 检查完成或退款业务对应的业务状态
     * 允许退款：待接单
     * 允许完成：进行中
     * @param business 业务对象
     * @param isRefund 是否为退款业务
     */
    private static void checkCompleteOrRefundBusiness(Business business, boolean isRefund) {
        // 1、业务状态
        BusinessStatus businessStatus = business.getStatus();

        // 2、未接单（允许退款，不允许完成）
        if (!isRefund && businessStatus == BusinessStatus.UNACCEPTED) {
            throw new BusinessErrorException(MessageConstant.BUSINESS_UNACCEPTED);
        }

        // 3、进行中（不允许退款，允许完成）
        if (isRefund && businessStatus == BusinessStatus.IN_PROGRESS) {
            throw new BusinessErrorException(MessageConstant.BUSINESS_IN_PROGRESS);
        }

        // 3、已完成（不允许退款，不允许完成）
        if (businessStatus == BusinessStatus.COMPLETED) {
            throw new BusinessErrorException(MessageConstant.BUSINESS_COMPLETED);
        }

        // 4、已退款（不允许退款，不允许完成）
        if (businessStatus == BusinessStatus.REFUNDED) {
            throw new BusinessErrorException(MessageConstant.BUSINESS_REFUNDED);
        }
    }

}
